import { PlusOutlined } from "@ant-design/icons";
import { message, Upload, Modal } from "antd";
import React, { useEffect, useState, useImperativeHandle } from "react";
import axios from "axios";

const getBase64 = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = () => resolve(reader.result);

    reader.onerror = (error) => reject(error);
  });

const PictureWall = ({ value, onChange }, ref) => {
  const [OSSData, setOSSData] = useState();
  let [token, setToken] = useState("");
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [previewTitle, setPreviewTitle] = useState("");

  const reqToken = async () => {
    const result = await axios.post(
      "http://api.shop.eduwork.cn/api/auth/login",
      { email: "super@a.com", password: "123123" }

      //{ email: "1161837921@qq.com", password: "23456!" }
    );
    token = "Bearer " + result.data.access_token;

    setToken(token);
    init();
  };

  const init = async () => {
    try {
      const result = await axios.get(
        "http://api.shop.eduwork.cn/api/auth/oss/token",
        {
          headers: {
            Authorization: token,
          },
        }
      );
      // console.log(result.data);
      setOSSData(result.data);
    } catch (error) {
      message.error(error);
    }
  };

  useEffect(() => {
    reqToken();
    // eslint-disable-next-line
  }, []);

  const handleChange = ({ fileList }) => {
    onChange?.([...fileList]);
  };

  const getExtraData = (file) => {
    return {
      key: file.key,
      OSSAccessKeyId: OSSData?.accessid,
      policy: OSSData?.policy,
      Signature: OSSData?.signature,
    };
  };

  // 向父组件传递方法
  useImperativeHandle(ref, () => ({ handleChange }));

  const beforeUpload = async (file) => {
    if (!OSSData) return false;
    const expire = Number(OSSData.expire) * 1000;

    //如果签名过期了，需重新获取
    if (expire < Date.now()) {
      await init();
    }

    //自定义目录
    const dir = "react/";

    const suffix = file.name.slice(file.name.lastIndexOf("."));
    const filename = Date.now() + suffix; // @ts-ignore

    // 在getExtraData（） 中用到，云存储时存储的key
    file.key = OSSData.dir + dir + filename;
    // 上传完成后，用于预览图片preview
    file.url = OSSData.host + OSSData.dir + dir + filename;
    return file;
  };

  // 操作modal
  const handleCancel = () => setPreviewVisible(false);
  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    setPreviewImage(file.url || file.preview);
    setPreviewVisible(true);
    setPreviewTitle(
      file.name || file.url.substring(file.url.lastIndexOf("/") + 1)
    );
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );

  const uploadProps = {
    name: "file",
    fileList: value,
    action: OSSData?.host,
    onChange: handleChange,
    data: getExtraData,
    beforeUpload,
    listType: "picture-card",
    onPreview: handlePreview,
    maxCount: 1, // 允许上传的数量
    accept: "image/*", // 默认任何类型的文件/文件夹都可以上传
  };
  return (
    <>
      <Upload {...uploadProps}>{uploadButton}</Upload>
      <Modal
        visible={previewVisible}
        title={previewTitle}
        footer={null}
        onCancel={handleCancel}
      >
        <img
          alt="example"
          style={{
            width: "100%",
          }}
          src={previewImage}
        />
      </Modal>
    </>
  );
};

export default React.forwardRef(PictureWall);
